rm(list = ls())
library(reshape2)
library(magrittr)
library(stringr)
library(CADFtest)

cnt <- openxlsx::read.xlsx('data-raw/country3code.xlsx',2)
pat <- openxlsx::read.xlsx('data-raw/主要国家PCT专利申请量_月.xlsx',1, rows = 1:243, detectDate = T)
pat <- melt(pat, id.vars = '指标名称', value.name = 'pat',factorsAsStrings = FALSE, variable.name = 'cnt')

pat$cnt <- str_split_fixed(pat$cnt,':',2) %>% .[,2]
pat <- merge(pat, cnt, by.x = 'cnt', by.y = 'cntnm', all = T)
pat <- pat[pat$指标名称 <= as.Date('2017-12-31') & pat$指标名称 >= as.Date('2000-12-31'),]
pat$yr <- format(pat$指标名称,'%Y')
pat$mon <- format(pat$指标名称,'%m')
pat$date <- paste(pat$yr,'M' ,pat$mon, sep = '')
pat <- pat[!is.na(pat$cntcd),]
pat <- dcast(pat, date ~ cntcd, value.var = 'pat')
pat[pat == 0] <- 0.5
pat[,-1] <- log(pat[,-1])

intc <- 1:nrow(pat)
for (i in 2:ncol(pat)) {
  # 去趋势
  pat[,i] <- lm(pat[,i] ~ intc) %>% residuals()
  ans <- CADFtest(pat[,i],type = 'drift', max.lag.y = 3) %>% .[['p.value']]
  if (ans > 0.05) {
    print(names(pat)[i])
    pat[,i] <- c(NA, diff(pat[,i]))
  }
}

# save(pat, file = 'data-raw/pat.rdata')

